package com.fwj.authorization.security;

import com.fwj.authorization.staff.entity.SysPermission;
import com.fwj.authorization.staff.entity.SysRole;
import com.fwj.authorization.staff.entity.SysUser;
import com.fwj.authorization.staff.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author fwj
 * @date 2025/03/18
 */
@Slf4j
@Service
public class SysUserDetailsService implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        log.info("用户存在，用户:{}", username);
        List<SysRole> roleList = sysUserService.getRoleListByUsername(user.getUsername());
        List<SimpleGrantedAuthority> userGrantedAuthorities = createAuthorities(roleList);
        List<SysPermission> permissionList = sysUserService.getPermissionListByUsername(user.getUsername());
        List<String> rolePrem = createRolePrem(permissionList);
        //返回数据对象(手动已加密)
        return new LoginUser(user.getId(),
                null,
                "FWJ",
                user.getUsername(),
                user.getRealName(),
                user.getPwd(),
                true, true, true, true,
                userGrantedAuthorities,
                user.getType(), rolePrem);
    }

    private List<SimpleGrantedAuthority> createAuthorities(List<SysRole> roleList) {
        List<SimpleGrantedAuthority> userGrantedAuthorities = new ArrayList<SimpleGrantedAuthority>();
        for (SysRole role : roleList) {
            userGrantedAuthorities.add(new SimpleGrantedAuthority(role.getCode()));
            log.info("role:{}", role);
        }
        return userGrantedAuthorities;
    }

    private List<String> createRolePrem(List<SysPermission> permissionList) {
        List<String> rolePrem = new ArrayList<>();
        for (SysPermission sysPermission : permissionList) {
            String roleCode = sysPermission.getRoleCode();
            String url = sysPermission.getUrl();
            if (roleCode != null && url != null) {
                // 角色权限码 roleCode[/user/page]
                rolePrem.add(roleCode + "[" + url + "]");
            }
        }
        return rolePrem;
    }
}
